//
//  ConversationListDataBase.m
//  AAIM
//
//  Created by awh on 2019/12/23.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "ConversationListDataBase.h"
#import "ConversationManager.h"

#import "BTMessageModel.h"
#import "TextMessageModel.h"
#import "ImageMessageModel.h"
#import "VoiceMessageModel.h"
@interface ConversationListDataBase ()

//@property(nonatomic, strong) FMDatabase *db;   // 数据库，存储多张表
@property(nonatomic, copy) NSString *tableName; // 表名，每个用户对应一个会话列表

@property(nonatomic, strong) FMDatabaseQueue *dbQueue; // 数据库线程

@end
@implementation ConversationListDataBase
//SingleM(ConversationListDataBase);

static ConversationListDataBase *single = nil;
+ (instancetype)shareConversationListDataBase {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        single = [[self alloc] init];
    });
    return single;
    
}

- (instancetype)init {
    if (self = [super init]) {
        [self initDataBase];
    }
    return self;
}
- (void)initDataBase {
    // 1.创建database路径
    NSString *docuPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *dbPath = [docuPath stringByAppendingPathComponent:@"chatMessage.db"];
    
    [CacheTool saveUserDefaults:@"APPDATABASE_KEY" dataObj:dbPath];
    
    self.dbQueue = [FMDatabaseQueue databaseQueueWithPath:dbPath];
}
- (void)createTable {
    
    // keyid :(好友还是群_id)
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *createTableSql = [NSString stringWithFormat:@"create table if not exists %@ ('keyid' TEXT, 'type' TEXT, 'messageDirection' INTEGER, 'messageType' INTEGER, 'uid' INTEGER, 'username' TEXT, 'avatar' TEXT, 'content' TEXT, 'src' TEXT, 'groupId' INTEGER, 'timestamp' INTEGER, 'unreadCount' INTEGER, 'offlineUnreadCount' INTEGER, 'ignore' INTEGER, 'top' INTEGER, 'topTimestamp' INTEGER, 'isAt' INTEGER, 'updateTimestamp' INTEGER, 'msgtype' INTEGER, 'msg_id' TEXT, 'clientuuid' TEXT, 'createtime' TEXT, 'msg' TEXT, 'gId' TEXT, 'head' TEXT, 'f_uuid' TEXT, 'nickname' TEXT, 'token' TEXT, 'udid' TEXT, 'rfuuid' TEXT, 'chatType' INTEGER ,'type_id' INTEGER ,'ishow' TEXT ,'groupHead' TEXT , 'groupName' TEXT)", self.tableName];
        [db executeUpdate:createTableSql];
    }];
}

// 查找当前登录用户的全部会话
- (void)saveConversation:(BTMessageModel *)msg {
  BTMessageModel *origin = [self queryConversationWithKeyid:[self keyidOfMessage:msg]];
   if (msg.chatType == ChatTypeFriend || msg.chatType == ChatTypeGroup) {
     if (origin) {
        if (origin.timestamp < msg.timestamp || msg.messageType == MessageTypeRecall) { // 会话是最新的
            msg.unreadCount += origin.unreadCount;
            msg.offlineUnreadCount += origin.offlineUnreadCount;
            msg.isAt = origin.isAt ? YES : NO;
            BOOL isAt = [msg.msg containsString:kAtDividedSymbols];
            if (isAt) {
                msg.isAt = [self isAtSelf:msg.msg] || [self isAtSelf:origin.msg];
            };
            [self updateMessage:msg];
        } else { // 会话不是最新的
            origin.unreadCount += msg.unreadCount;
            origin.offlineUnreadCount += msg.offlineUnreadCount;
            if (!origin.isAt) {
                BOOL isAt = [msg.msg containsString:kAtDividedSymbols];
                origin.isAt = isAt;
            }
            [self updateMessage:origin];
        }
    } else {
        msg.isAt = [self isAtSelf:msg.msg];
        [self insertMessage:msg];
    }
    if (msg.messageDirection == MessageDirectionSend) {
        [self clearUnreadCount:msg];
    }
    }else
    {
        //通知
        if (origin) { // 新的会话
//            if (msg.type_id == SystemMessageApplyCreateGroup|| msg.type_id ==  SystemMessageAuditCreateGroup || msg.type_id ==  SystemMessageDeleteGroup || msg.type_id ==  SystemMessageApplyJoinGroup || msg.type_id ==  SystemMessageAuditJoinGroup || msg.type_id ==  SystemMessageRefusedJoinGroup) {
                if (origin.timestamp < msg.timestamp )
                {
                    [self updateMessage:msg];
                }else
                {
                    [self updateMessage:origin];
                }
            }else
            {
                [self insertMessage:msg];
            }
        
    }
    
}

- (BOOL)isAtSelf:(NSString *)content {
    BOOL isAtMsg = [content containsString:kAtDividedSymbols];
    if (!isAtMsg) {
        return NO;
    }
    NSArray<NSString *> *components = [content componentsSeparatedByString:kAtDividedSymbols];
    NSString *idsStr = components[1];
    __block BOOL isAtSelf = NO;
    if ([idsStr isEqualToString:kAtAllSymbols]) {
        isAtSelf = YES;
    } else {
        NSArray<NSString *> *ids = [idsStr componentsSeparatedByString:@","];
        [ids enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSInteger uid = obj.integerValue;
            if (uid == [LoginManager shareLoginManager].userModel.fuuid.integerValue) {
                isAtSelf = YES;
                *stop = YES;
            }
        }];
    }
    return isAtSelf;
}

// 获取全部会话信息
- (NSArray<BTMessageModel *> *)queryAllConversations {
    NSMutableArray *conversations = [NSMutableArray new];
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        // 清空超过三小时的消息
       /* long long fromTime = [ChatTool shareChatTool].currentTimestamp - 3 * 60 * 60 * 1000;
        NSString *deleteSql = [NSString stringWithFormat:@"update %@ set content = '', messageType = 1, unreadCount = 0, offlineUnreadCount = 0 where updateTimestamp < %lld", self.tableName, fromTime];
        [db executeUpdate:deleteSql];*/
        // 获取全部会话信息
//        NSString *sql = [NSString stringWithFormat:@"select * from %@ order by top desc, topTimestamp desc, timestamp desc;", self.tableName];
        NSString *sql = [NSString stringWithFormat:@"select * from %@ ;", self.tableName];

        FMResultSet *result = [db executeQuery:sql];
        while ([result next]) {
            [conversations addObject:[self messageWith:result]];
        }
    }];
    return conversations;
}

// 获取单条会话信息
- (BTMessageModel *)converationWithChatType:(ChatType)chatType uidOrGroupId:(NSInteger)uidOrGroupId {
    NSString *keyid = chatType == ChatTypeFriend ? [NSString stringWithFormat:@"friend_%ld", uidOrGroupId] :  [NSString stringWithFormat:@"group_%ld", uidOrGroupId];
    NSMutableArray *conversations = [NSMutableArray new];
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"select * from %@ where keyid = '%@';", self.tableName, keyid];
        FMResultSet *result = [db executeQuery:sql];
        while ([result next]) {
            [conversations addObject:[self messageWith:result]];
        }
    }];
    if (conversations.count) {
        BTMessageModel *msg = [conversations firstObject];
        return msg;
    } else {
        return nil;
    }
}

- (NSInteger)totalUnreadCount {
    /*
     __block NSInteger total = 0;
     NSArray<BTMessageModel *> *messages = [self queryAllConversations];
     [messages enumerateObjectsUsingBlock:^(BTMessageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
     if (!obj.ignore) {
     NSArray<NSString *> *conponents = [obj.keyid componentsSeparatedByString:@"_"];
     if (conponents.count == 2) {
     NSInteger type = [conponents[0] isEqualToString:@"friend"] ? 1 : 2;
     NSInteger friendOrGroupId = conponents[1].integerValue;
     BOOL isIn = [[LoginManager shareLoginManager].userDataBase isAlreadyHaveUserOrGroupWithID:friendOrGroupId istype:type];
     if (isIn) {
     total += (obj.unreadCount + obj.offlineUnreadCount);
     }
     }
     }
     }];
     return total;
     */
    __block NSInteger total = 0;
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        // 清空超过三小时的消息
//        long long fromTime = [ChatTool shareChatTool].currentTimestamp - 3 * 60 * 60 * 1000;
//        NSString *deleteSql = [NSString stringWithFormat:@"update %@ set content = '', messageType = 1, unreadCount = 0, offlineUnreadCount = 0 where updateTimestamp < %lld", self.tableName, fromTime];
//        [db executeUpdate:deleteSql];
        // 获取全部会话信息
        NSString *sql = [NSString stringWithFormat:@"select * from %@ where ignore = 0 order by top desc, topTimestamp desc, timestamp desc;", self.tableName];
        FMResultSet *result = [db executeQuery:sql];
        while ([result next]) {
            BTMessageModel *obj = [self messageWith:result];
            total += (obj.unreadCount + obj.offlineUnreadCount);
        }
    }];
    return total;
}

// 插入
- (void)insertMessage:(BTMessageModel *)msg {
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *tableNameHead = [NSString stringWithFormat:@"insert into '%@' ", self.tableName];
        NSString *keyId = [self keyidOfMessage:msg];
        BOOL result = NO;
        long long updateTime = [ChatTool shareChatTool].currentTimestamp;
        if (msg.messageDirection == MessageDirectionSend) { // 发送
              if (msg.chatType==ChatTypeFriend){
                  NSString *content = [NSString stringWithFormat:@"(keyid, type, messageDirection, messageType, uid, username, avatar, content, timestamp, unreadCount, offlineUnreadCount, ignore, top, topTimestamp, isAt, updateTimestamp, msg ,type_id ,msgtype ,rfuuid, f_uuid,nickname,chatType,groupHead,groupName) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? , ? ,? , ?, ?, ?, ?, ?, ?, ?)"];;
                NSString *sql = [NSString stringWithFormat:@"%@%@", tableNameHead, content];
                result = [db executeUpdate:sql, keyId, msg.type, @(msg.messageDirection), @(msg.messageType), @(msg.uid), msg.username, msg.avatar, msg.content, @(msg.timestamp), @(msg.unreadCount), @(msg.offlineUnreadCount), @(msg.ignore), @(msg.top), @(msg.topTimestamp), @(msg.isAt), @(updateTime), msg.msg,@(msg.type_id),@(msg.msgtype),msg.rfuuid,msg.f_uuid,msg.nickname,@(msg.chatType),msg.groupHead,msg.groupName];
            } else  if (msg.chatType==ChatTypeGroup){
                NSString *content = [NSString stringWithFormat:@"(keyid, type, messageDirection, messageType, uid, username, content, groupId, timestamp, unreadCount, offlineUnreadCount, ignore, top, topTimestamp, isAt, updateTimestamp, msg, gId , head ,chatType,msgtype,groupHead,groupName) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,? ,?)"];
                NSString *sql = [NSString stringWithFormat:@"%@%@", tableNameHead, content];
                result = [db executeUpdate:sql, keyId, msg.type,  @(msg.messageDirection), @(msg.messageType), @(msg.uid), msg.username, msg.content, @(msg.receiveUid), @(msg.timestamp), @(msg.unreadCount), @(msg.offlineUnreadCount), @(msg.ignore), @(msg.top), @(msg.topTimestamp), @(msg.isAt), @(updateTime),msg.msg,msg.gId,msg.head,@(msg.chatType),@(msg.msgtype),msg.groupHead,msg.groupName];
            }else if (msg.chatType==ChatTypeSystem)
            {
                NSString *content = [NSString stringWithFormat:@"(keyid, type, messageDirection, messageType, uid, username, avatar, content, timestamp, unreadCount, offlineUnreadCount, ignore, top, topTimestamp, isAt, updateTimestamp, msg ,type_id ,msgtype ,rfuuid, f_uuid,nickname,chatType ,gId) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? , ? ,? , ?, ?, ?, ?, ?, ?)"];;
                NSString *sql = [NSString stringWithFormat:@"%@%@", tableNameHead, content];
                result = [db executeUpdate:sql, keyId, msg.type, @(msg.messageDirection), @(msg.messageType), @(msg.uid), msg.username, msg.avatar, msg.content, @(msg.timestamp), @(msg.unreadCount), @(msg.offlineUnreadCount), @(msg.ignore), @(msg.top), @(msg.topTimestamp), @(msg.isAt), @(updateTime), msg.msg,@(msg.type_id),@(msg.msgtype),msg.rfuuid,msg.f_uuid,msg.nickname,@(msg.chatType),msg.gId];
            }
        } else { // 接收
            if (msg.chatType==ChatTypeFriend){
                NSString *content = [NSString stringWithFormat:@"(keyid, type, messageDirection, messageType, uid, username, avatar, content, timestamp, unreadCount, offlineUnreadCount, ignore, top, topTimestamp, isAt, updateTimestamp,msg ,type_id ,msgtype ,rfuuid, f_uuid,nickname,chatType,groupHead,groupName) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? , ? ,? , ?, ?, ?, ? ,? ,? ,?)"];
                NSString *sql = [NSString stringWithFormat:@"%@%@", tableNameHead, content];
                result = [db executeUpdate:sql, keyId, msg.type, @(msg.messageDirection), @(msg.messageType), @(msg.uid), msg.username, msg.avatar, msg.content, @(msg.timestamp), @(msg.unreadCount), @(msg.offlineUnreadCount), @(msg.ignore), @(msg.top), @(msg.topTimestamp), @(msg.isAt), @(updateTime), msg.msg,@(msg.type_id),@(msg.msgtype),msg.rfuuid,msg.f_uuid,msg.nickname,@(msg.chatType),msg.groupHead,msg.groupName];
            } else if (msg.chatType == ChatTypeGroup){
                NSString *content = [NSString stringWithFormat:@"(keyid, type, messageDirection, messageType, uid, username, avatar, content, src, groupId, timestamp, unreadCount, offlineUnreadCount, ignore, top, topTimestamp, isAt, updateTimestamp , msg, gId , head ,chatType ,msgtype,groupHead,groupName) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,? ,? ,? ,? ,?)"];
                NSString *sql = [NSString stringWithFormat:@"%@%@", tableNameHead, content];
                NSString *avatar = [NSObject ldy_isEmpty:msg.avatar] ? @"" : msg.avatar;
                NSString *src = [NSObject ldy_isEmpty:msg.src] ? @"" : msg.src;
                result = [db executeUpdate:sql, keyId, msg.type, @(msg.messageDirection), @(msg.messageType), @(msg.uid), msg.username, avatar, msg.content, src, @(msg.groupId), @(msg.timestamp), @(msg.unreadCount), @(msg.offlineUnreadCount), @(msg.ignore), @(msg.top), @(msg.topTimestamp), @(msg.isAt), @(updateTime),msg.msg,msg.gId,msg.head,@(msg.chatType),@(msg.msgtype),msg.groupHead,msg.groupName];
            }else if (msg.chatType == ChatTypeSystem)
            {
                NSString *content = [NSString stringWithFormat:@"(keyid, type, messageDirection, messageType, uid, username, avatar, content, timestamp, unreadCount, offlineUnreadCount, ignore, top, topTimestamp, isAt, updateTimestamp, msg ,type_id ,msgtype ,rfuuid, f_uuid,nickname,chatType,gId) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? , ? ,? , ?, ?, ? , ? , ?, ?)"];;
                NSString *sql = [NSString stringWithFormat:@"%@%@", tableNameHead, content];
                result = [db executeUpdate:sql, keyId, msg.type, @(msg.messageDirection), @(msg.messageType), @(msg.uid), msg.username, msg.avatar, msg.content, @(msg.timestamp), @(msg.unreadCount), @(msg.offlineUnreadCount), @(msg.ignore), @(msg.top), @(msg.topTimestamp), @(msg.isAt), @(updateTime), msg.msg,@(msg.type_id),@(msg.msgtype),msg.rfuuid,msg.f_uuid,msg.nickname,@(msg.chatType),msg.gId];
            }
        }
    }];
}

// 更新
- (void)updateMessage:(BTMessageModel *)msg {
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *tableNameHead = [NSString stringWithFormat:@"update '%@' ",self.tableName];
        NSString *keyid = [self keyidOfMessage:msg];
        BOOL result = NO;
        long long updateTime = [ChatTool shareChatTool].currentTimestamp;
        if (msg.messageDirection == MessageDirectionSend) { // 发送
            if ( msg.chatType == ChatTypeFriend) {
                NSString *content = [NSString stringWithFormat:@" set type = '%@', messageDirection = %@, messageType = %@, uid = %@, username = '%@', avatar = '%@', content = '%@', timestamp = %@, unreadCount = %@, offlineUnreadCount = %@, isAt = %@, updateTimestamp = %@ ,msg = '%@' , chatType = %@ , rfuuid = '%@', f_uuid = '%@', msgtype= %@ ,type_id=%@ ,groupHead = '%@' ,groupName = '%@' where (keyid = '%@')", msg.type, @(msg.messageDirection), @(msg.messageType), @(msg.uid), msg.username, msg.avatar, msg.content, @(msg.timestamp), @(msg.unreadCount), @(msg.offlineUnreadCount), @(msg.isAt), @(updateTime),msg.msg,@(msg.chatType),msg.rfuuid,msg.f_uuid,@(msg.msgtype),@(msg.type_id),msg.groupHead,msg.groupName,keyid];
                NSString *sql = [NSString stringWithFormat:@"%@%@", tableNameHead, content];
                result = [db executeUpdate:sql];
            } else  if (msg.chatType == ChatTypeGroup){
                NSString *content = [NSString stringWithFormat:@"set type = '%@', messageDirection = %@, messageType = %@, uid = %@, username = '%@', content = '%@', groupId = %@, timestamp = %@, unreadCount = %@, offlineUnreadCount = %@, isAt = %@, updateTimestamp = %@ , msg = '%@' , gId = '%@' ,head ='%@', chatType = %@ , msgtype = %@ ,type_id=%@ ,groupHead = '%@' ,groupName = '%@' where (keyid = '%@')",msg.type,  @(msg.messageDirection), @(msg.messageType), @(msg.uid), msg.username, msg.content, @(msg.receiveUid), @(msg.timestamp), @(msg.unreadCount), @(msg.offlineUnreadCount), @(msg.isAt), @(updateTime),msg.msg,msg.gId,msg.head,@(msg.chatType),@(msg.msgtype),@(msg.type_id) ,msg.groupHead,msg.groupName,keyid];
                NSString *sql = [NSString stringWithFormat:@"%@%@", tableNameHead, content];
                result = [db executeUpdate:sql];
            }else if (msg.chatType == ChatTypeSystem)
            {
                NSString *content = [NSString stringWithFormat:@"set type = '%@', messageDirection = %@, messageType = %@, uid = %@, username = '%@', content = '%@', groupId = %@, timestamp = %@, unreadCount = %@, offlineUnreadCount = %@, isAt = %@, updateTimestamp = %@ , msg = '%@' , gId = '%@' ,head ='%@',chatType = %@ , msgtype = %@ ,type_id = %@ where (keyid = '%@')",msg.type,  @(msg.messageDirection), @(msg.messageType), @(msg.uid), msg.username, msg.content, @(msg.receiveUid), @(msg.timestamp), @(msg.unreadCount), @(msg.offlineUnreadCount), @(msg.isAt), @(updateTime),msg.msg,msg.gId,msg.head,@(msg.chatType),@(msg.msgtype) ,@(msg.type_id),keyid];
                NSString *sql = [NSString stringWithFormat:@"%@%@", tableNameHead, content];
                result = [db executeUpdate:sql];
            }
        } else { // 接收
            if (msg.chatType == ChatTypeFriend) {
                NSString *content = [NSString stringWithFormat:@"set type = '%@', messageDirection = '%@', messageType = '%@', uid = '%@', username = '%@', avatar = '%@', content = '%@', timestamp = '%@', unreadCount =  '%@', offlineUnreadCount = %@, isAt = %@, updateTimestamp = %@ ,msg = %@ , chatType = %@ , rfuuid = '%@', f_uuid = '%@', msgtype= %@ , type_id = %@ ,groupHead = '%@' ,groupName = '%@' where (keyid = '%@')",  msg.type, @(msg.messageDirection), @(msg.messageType), @(msg.uid), msg.username, msg.avatar, msg.content, @(msg.timestamp), @(msg.unreadCount), @(msg.offlineUnreadCount), @(msg.isAt), @(updateTime), msg.msg ,@(msg.chatType),msg.rfuuid,msg.f_uuid,@(msg.msgtype),@(msg.type_id),msg.groupHead,msg.groupName,keyid];
                NSString *sql = [NSString stringWithFormat:@"%@%@", tableNameHead, content];
                result = [db executeUpdate:sql];
            } else if (msg.chatType == ChatTypeGroup) {
                NSString *content = [NSString stringWithFormat:@"set type = '%@', messageDirection = %@, messageType = %@, uid = %@, username = '%@', content = '%@', groupId = %@, timestamp = %@, unreadCount = %@, offlineUnreadCount = %@,  isAt = %@, updateTimestamp = %@ , msg = '%@' , gId = '%@' ,head ='%@', chatType = %@ , msgtype = %@ ,type_id =%@ ,groupHead = '%@' ,groupName = '%@' where (keyid = '%@')", msg.type, @(msg.messageDirection), @(msg.messageType), @(msg.uid), msg.username, msg.content, @(msg.groupId), @(msg.timestamp),  @(msg.unreadCount), @(msg.offlineUnreadCount), @(msg.isAt), @(updateTime),msg.msg,msg.gId,msg.head,@(msg.chatType),@(msg.msgtype),@(msg.type_id), msg.groupHead,msg.groupName,keyid];
                NSString *sql = [NSString stringWithFormat:@"%@%@", tableNameHead, content];
                result = [db executeUpdate:sql];
            }else if (msg.chatType == ChatTypeSystem)
            {
                NSString *content = [NSString stringWithFormat:@"set type = '%@', messageDirection = %@, messageType = %@, uid = %@, username = '%@', content = '%@', groupId = %@, timestamp = %@, unreadCount = %@, offlineUnreadCount = %@, isAt = %@, updateTimestamp = %@ , msg = '%@' , gId = '%@' ,head ='%@',chatType = %@ , msgtype = %@ ,type_id = %@ where (keyid = '%@')",msg.type,  @(msg.messageDirection), @(msg.messageType), @(msg.uid), msg.username, msg.content, @(msg.receiveUid), @(msg.timestamp), @(msg.unreadCount), @(msg.offlineUnreadCount), @(msg.isAt), @(updateTime),msg.msg,msg.gId,msg.head,@(msg.chatType),@(msg.msgtype) ,@(msg.type_id),keyid];
                NSString *sql = [NSString stringWithFormat:@"%@%@", tableNameHead, content];
                result = [db executeUpdate:sql];
                
            }
        }
    }];
}

// 清空content，用于删除聊天记录时使用
- (void)clearConversationContentWithChatType:(ChatType)chatType uidOrGroupId:(NSInteger)uidOrGroupId {
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *keyid = chatType == ChatTypeFriend ? [NSString stringWithFormat:@"friend_%ld", uidOrGroupId] :  [NSString stringWithFormat:@"group_%ld", uidOrGroupId];
        NSString *sql = [NSString stringWithFormat:@"update %@ set content = '', messageType = 1, unreadCount = 0, offlineUnreadCount = 0 where keyid = '%@'", self.tableName, keyid];
        [db executeUpdate:sql];
    }];
    [[ConversationManager shareManager] reloadData];
}


// 删除
- (void)deleteConversationWithChatType:(ChatType)chatType uidOrGroupId:(NSInteger)uidOrGroupId {
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *keyid = chatType == ChatTypeFriend ? [NSString stringWithFormat:@"friend_%ld", uidOrGroupId] :  [NSString stringWithFormat:@"group_%ld", uidOrGroupId];
        NSString *sql = [NSString stringWithFormat:@"delete from %@ where keyid = '%@'", self.tableName, keyid];
        [db executeUpdate:sql];
    }];
    [[ConversationManager shareManager] reloadData];
}

// 根据keyid删除
- (void)deleteConversationWithKeyid:(NSString *)keyid {
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"delete from %@ where keyid = '%@'", self.tableName, keyid];
        [db executeUpdate:sql];
    }];
    [[ConversationManager shareManager] reloadData];
}

// 清空会话列表
- (void)clearConversations {
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"update %@ set content = '', messageType = 1, unreadCount = 0, offlineUnreadCount = 0", self.tableName];
        [db executeUpdate:sql];
    }];
    [[ConversationManager shareManager] reloadData];
}

/**
 更新提醒状态
 
 @param chatType 单聊或群聊
 @param uidOrGroupId 单聊为对方id， 群聊为群id
 @param isIgnore 是否屏蔽通知
 */
- (void)updateMessageIgnoreStatusWithChatType:(ChatType)chatType uidOrGroupId:(NSInteger)uidOrGroupId isIgnore:(BOOL)isIgnore {
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *keyid = chatType == ChatTypeFriend ? [NSString stringWithFormat:@"friend_%ld", uidOrGroupId] :  [NSString stringWithFormat:@"group_%ld", uidOrGroupId];
        NSString *sql = [NSString stringWithFormat:@"update %@ set ignore = %d where keyid = '%@'", self.tableName, isIgnore, keyid];
        [db executeUpdate:sql];
    }];
    [[ConversationManager shareManager] reloadData];
}

/**
 更新是否置顶聊天
 
 @param chatType 单聊或群聊
 @param uidOrGroupId 单聊为对方id， 群聊为群id
 @param isTop 是否置顶
 */
- (void)updateConversationTopStatusWithChatType:(ChatType)chatType uidOrGroupId:(NSInteger)uidOrGroupId isTop:(BOOL)isTop {
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *keyid = chatType == ChatTypeFriend ? [NSString stringWithFormat:@"friend_%ld", (long)uidOrGroupId] :  [NSString stringWithFormat:@"group_%ld", (long)uidOrGroupId];
        long long topTimestamp = isTop ? [ChatTool shareChatTool].currentTimestamp : 0;
        NSString *sql = [NSString stringWithFormat:@"update %@ set top = %d, topTimestamp = %lld where keyid = '%@'", self.tableName, isTop, topTimestamp, keyid];
        [db executeUpdate:sql];
    }];
    [[ConversationManager shareManager] reloadData];
}

// 根据时间戳清空该消息的未读消息数
- (void)clearUnreadCount:(BTMessageModel *)msg {
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *keyid = [self keyidOfMessage:msg];
        NSString *sql = [NSString stringWithFormat:@"update %@ set unreadCount = 0, offlineUnreadCount = 0 where keyid = '%@';", self.tableName, keyid];
        [db executeUpdate:sql];
    }];
}

// 清除@
- (void)clearAtWithMessage:(BTMessageModel *)msg {
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *keyid = [self keyidOfMessage:msg];
        NSString *sql = [NSString stringWithFormat:@"update %@ set isAt = 0 where keyid = '%@';", self.tableName, keyid];
        [db executeUpdate:sql];
    }];
    [[ConversationManager shareManager] reloadData];
}

- (BTMessageModel *)queryConversationWithKeyid:(NSString *)keyid {
    NSMutableArray *conversations = [NSMutableArray new];
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"select * from %@ where keyid = '%@';", self.tableName, keyid];
        FMResultSet *result = [db executeQuery:sql];
        while ([result next]) {
            [conversations addObject:[self messageWith:result]];
        }
    }];
    if (conversations.count > 0) {
        return conversations[0];
    } else {
        return nil;
    }
}


- (NSString *)keyidOfMessage:(BTMessageModel *)msg {
    NSString *keyid = @"";
    if (msg.messageDirection == MessageDirectionSend) {
        if (msg.chatType==ChatTypeFriend) {
            keyid = [NSString stringWithFormat:@"friend_%@", msg.rfuuid];
        }else
        {
            keyid = [NSString stringWithFormat:@"group_%@", msg.gId];
        }

    } else {
        if (msg.chatType==ChatTypeFriend) {
//            keyid = [NSString stringWithFormat:@"friend_%@", msg.f_uuid];
            if ([NSObject ldy_isEmpty:msg.f_uuid]) {
                keyid = [NSString stringWithFormat:@"friend_%@", msg.fuuid];
            }else
            {
                keyid = [NSString stringWithFormat:@"friend_%@", msg.f_uuid];
            }
        } else if (msg.chatType==ChatTypeGroup) {
            keyid = [NSString stringWithFormat:@"group_%@", msg.gId];
        } else if (msg.chatType==ChatTypeSystem) {
            if (msg.receiveUid==0) {
                if (msg.groupId==0) {
                    keyid=msg.keyid;
                }else
                {
                    keyid = [NSString stringWithFormat:@"sys_%ld", msg.groupId];
                }
            }else
            {
                if (msg.groupId==0) {
                    keyid = [NSString stringWithFormat:@"sys_%ld", msg.receiveUid];
                }else
                {
                    keyid=msg.keyid;
                }
            }
        }
    }
    return keyid;
}

- (BTMessageModel *)messageWith:(FMResultSet *)result {
    BTMessageModel *msg = [BTMessageModel new];
    msg.keyid = [result stringForColumn:@"keyid"];
    msg.messageType = [result intForColumn:@"messageType"];
    msg.messageDirection = [result intForColumn:@"messageDirection"];
    msg.uid = [result intForColumn:@"uid"];
    msg.username = [result stringForColumn:@"username"];
    msg.avatar = [result stringForColumn:@"avatar"];
    msg.type = [result stringForColumn:@"type"];
    msg.content = [result stringForColumn:@"content"];
    msg.src = [result stringForColumn:@"src"];
    msg.timestamp = [result longLongIntForColumn:@"timestamp"];
    msg.unreadCount = [result intForColumn:@"unreadCount"];
    msg.offlineUnreadCount = [result intForColumn:@"offlineUnreadCount"];
    msg.groupId = [result intForColumn:@"groupId"];
    msg.ignore = [result boolForColumn:@"ignore"];
    msg.top = [result boolForColumn:@"top"];
    msg.isAt = [result boolForColumn:@"isAt"];
    msg.updateTimestamp = [result longLongIntForColumn:@"updateTimestamp"];
    
    msg.msgtype=[result intForColumn:@"msgtype"];
    msg.msg_id=[result stringForColumn:@"msg_id"];
    msg.clientuuid= [result stringForColumn:@"clientuuid"];
    msg.msg = [result stringForColumn:@"msg"];
    msg.gId = [result stringForColumn:@"gId"];
    msg.head=[result stringForColumn:@"head"];
    msg.f_uuid=[result stringForColumn:@"f_uuid"];
    msg.nickname=[result stringForColumn:@"nickname"];
    msg.token=[result stringForColumn:@"token"];
    msg.udid=[result stringForColumn:@"udid"];
    msg.createtime=[result stringForColumn:@"createtime"];
    msg.chatType = [result intForColumn:@"chatType"];
    msg.rfuuid=[result stringForColumn:@"rfuuid"];
    msg.type_id=[result intForColumn:@"type_id"];
    msg.ishow=[result stringForColumn:@"ishow"];
    msg.groupHead=[result stringForColumn:@"groupHead"];
    msg.groupName=[result stringForColumn:@"groupName"];

    return msg;
}

#pragma mark - getter

- (NSString *)tableName {
    UserModel * model_user= [[LoginManager shareLoginManager] getLoginCustomer];
    return  [NSString stringWithFormat:@"t_conversationList_%@", model_user.fuuid];
}
@end
